import {PageContainer} from '@ant-design/pro-components';
import {
  getInterfaceInfoRandUsingGet,
  listInterfaceInfoByPageUsingGet, searchListInterfaceInfoByPageUsingGet
} from '@/services/api-backend/interfaceInfoController';
import {Tag, Tooltip, Spin, message, Card, Col, Row, Divider, Typography, Badge, Pagination, Button} from 'antd';
import React, {useCallback, useEffect, useState} from 'react';
import './index.less';
import style from './index.less';
import {history} from "@@/core/history";
import {RedoOutlined} from "@ant-design/icons"; // 用于样式处理
import PubSub from 'pubsub-js';
import {throttle} from "lodash";
import ScrollList from "@/pages/Index/components/ScrollList/ScrollList";
import ToTopList from "@/pages/Index/components/ToTopList/ToTopList";
import ScrollDemo from "@/pages/BidirectionalAnimation/ScrollDemo";

const cardStyle: React.CSSProperties = {
  width: 257,
  marginTop: 4,

};

const imgStyle: React.CSSProperties = {
  display: 'block',
  width: 60,
};
const apiFont1: React.CSSProperties = {
  color: "#1f2d3d",
  fontWeight: 700,
  // fontSize:16
}
const randStyle: React.CSSProperties = {
  textDecoration: "none",
  borderBottom: "2px solid #425AEF",
  color: "#363636",
  fontWeight: 700,
  padding: "0 7px",
  marginLeft: 5
}

/**
 * 主页
 * @constructor
 */
const Index: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [list, setList] = useState<API.InterfaceInfo[]>([]);
  const [total, setTotal] = useState<number>(0);
  const [currentPage, setCurrentPage] = useState(1); // 当前页码
  const [randData, setRandData] = useState<API.InterfaceInfo[]>([]);
  // searchTextMessage 搜索框参数
  const [searchTextMessage, setSearchTextMessage] = useState("")
  const pageSize = 10; // 每页显示的Card数量
  const newElement = document.getElementById("最新ApiList");
  const onPageChange = (page) => {
    setCurrentPage(page);
    // 更新分页后，页面滑倒到最新APIList
    setTimeout(() => scrollSmooth(), 400)
  };

  // 自定义分页渲染，去掉"上一页"和"下一页"按钮
  const itemRender = (page, type) => {
    if (type === 'prev' || type === 'next') {
      return null; // 返回null，隐藏“上一页”和“下一页”
    }
    return <a>{page}</a>; // 正常渲染页码
  };

  /**
   * 保证在点击分页时，可以滑动到 最新ApiList
   */
  const scrollSmooth = () => {
    if (newElement) {
      //scrollIntoView 的 { behavior: "smooth" } 参数确保页面平滑滚动到目标元素。
      newElement.scrollIntoView({behavior: "smooth", block: "start"});
    }
  }
  //
  const loadData = async (current = 1, pageSize = pageSize, searchText: string) => {
    setLoading(true);
    try {
      const res = await searchListInterfaceInfoByPageUsingGet({
        pageSize,
        current,
        status: 1,
        sortField: "createTime",
        sortOrder: "descend",
        searchText
      });

      setList(res.data?.records ?? []);
      setTotal(res.data?.total ?? 0);
    } catch (error) {
      message.error('删除失败.' + error.message);
    } finally {
      setLoading(false);
    }
  };
  const goToInterfaceViewById = (id) => {
    history.push(`/one/interface_info/${id}`);
  }

  /**
   * 随机API
   */
  const loadRandData = useCallback(
    throttle(async () => {
      try {
        const res = await getInterfaceInfoRandUsingGet({
          size: 1
        });
        if (res?.code === 0) {
          setRandData(res?.data || [])
        }
      } catch (e) {

      }
    }, 700), []);
  /**
   * 监听搜索框传来的关键词，通过关键词来进行查询
   */
  useEffect(() => {
    //订阅通信，联动搜索框组件
    const message = PubSub.subscribe('searchText', (msg, data) => {
      setSearchTextMessage(data)
    });


    loadRandData()
    //退出index.tsx时要取消订阅
    return () => {
      PubSub.unsubscribe(message);
    }


  }, []);
  //根据关键词刷新最新ApiList数据
  useEffect(() => {
    loadData(1, pageSize, searchTextMessage);
  }, [searchTextMessage]);

  useEffect(() => {
    loadData(currentPage, pageSize, searchTextMessage);
  }, [currentPage]);
  return (
    /*PageContainer：是 Ant Design Pro 中提供的一个组件，用于快速构建页面的容器
    。它提供了一些常用的布局和功能，例如面包屑导航、页面标题、操作区域等，
    可以帮助我们快速搭建页面的基本结构。*/
    <PageContainer title={'在线接口开发平台'}>
    {/*<ScrollDemo/>*/}
      {/*排行榜*/}
      <ToTopList/>
      <div style={{marginBottom: 24}}></div>
      {/*滚动List*/}
      <ScrollList/>
      <div style={{marginBottom: 24}}></div>
      {/*随机API*/}
      <div>
        <Row gutter={[16, 16]} justify="space-between">
          <Col>
            <h2 style={apiFont1}>随机API <Button type="link" icon={<RedoOutlined
              onClick={loadRandData} style={{color: "rgba(60, 60, 67, 0.6)"}}/>}></Button></h2>
          </Col>
          <Col>
            <h3 style={{color: "rgba(60, 60, 67, 0.6)", fontWeight: 700}}>免费定制API</h3>
          </Col>
        </Row>
        <Card  bordered={false}>
          <div id="最新ApiList" style={{fontSize: 17, display: "flex", alignItems: "center"}}>
            <Tooltip className="ellipsis-text ellipsis-text-2" placement="top" title={randData[0]?.description}>
              {randData[0]?.description}
            </Tooltip>
            {" - "}
            <strong style={{color: "#425AEF"}}> {randData[0]?.userName}</strong> 的API:
            <a style={randStyle}
               onClick={() => goToInterfaceViewById?.(randData[0]?.id)}>{randData[0]?.name}</a>
          </div>
        </Card>
      </div>
      <div style={{marginBottom: 24}}></div>
      {/*APIList*/}
      <div className="spin-container-index">
        <Row gutter={[16, 16]} justify="space-between">
          <Col>
            <h2 style={apiFont1}>最新ApiList </h2>
            <h4 style={{color: "rgba(60, 60, 67, 0.6)", fontWeight: 700}}><Tag color="error">最新</Tag>是最重要的运营基础，超多开发者入驻构建发展免费接口生态，持续更新独家原创接口，欢迎提交需求～
            </h4>
          </Col>
        </Row>
        <div style={{marginBottom: 8}}></div>
        <Spin tip="正在加载中..." size="large" spinning={loading}>
          <Row gutter={[16, 16]}>
            {
              list.map((item) => (
                // eslint-disable-next-line react/jsx-key
                <div style={{marginLeft: 4}}>
                  <Badge.Ribbon text={item?.free===0?"免费":"付费"} color={item?.free===0?"green":"purple"}>
                    <Col style={{paddingRight: 0}} key={item?.id} xs={{span: 24}} sm={{span: 12}} lg={{span: 6}}>
                      <Card onClick={() => goToInterfaceViewById?.(item.id)} hoverable style={cardStyle}>
                        <div style={{display: 'flex', alignItems: 'center'}}>
                          <Badge count={99} overflowCount={10}>
                            <img
                              alt="avatar"
                              src="https://img.88icon.com/download/jpg/20200917/b356eecbd7466587f2e405572bab885c_512_512.jpg!bg"
                              style={imgStyle}
                            />
                          </Badge>
                          <div style={{padding: 10, flex: 1}}>
                            <Typography.Title level={5} className="ellipsis-text">
                              {item.name}
                            </Typography.Title>
                          </div>
                        </div>
                      </Card>

                    </Col>
                  </Badge.Ribbon>
                </div>
              ))
            }
          </Row>
        </Spin>

      </div>
      <Divider style={{
        position: "relative",
        bottom: 0
      }}/>
      <Pagination
        align="center"
        hideOnSinglePage={true}
        current={currentPage} // 当前页
        pageSize={pageSize} // 每页显示数量
        total={total} // 总数
        showSizeChanger={false}// 隐藏选择条数的下拉框
        onChange={onPageChange} // 页码变化时调用
        itemRender={itemRender} // 自定义分页渲染
      />
    </PageContainer>
  );
};
export default Index;
